﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using DefeatEpidemic.Models;
using DefeatEpidemic.Common;
using LinqKit;
using DefeatEpidemic.Base;

namespace DefeatEpidemic.Controllers
{

    [SignFilter]
    public class FamiliesController : Controller
    {
        private readonly DefeatEpidemicContext _context;

        public FamiliesController(DefeatEpidemicContext context)
        {
            _context = context;
        }

        // GET: Families
        public IActionResult Index()
        {
            return View();
        }

        //[ValidateAntiForgeryToken]
        [HttpGet]
        public ActionResult GetList(string name, int pageindex=1, int pagesize=15)
        {
            Response resp = new Response();
            try
            {
                int start = (pageindex - 1) * pagesize;
                var where = PredicateBuilder.New<Family>(true);
                if (!string.IsNullOrEmpty(name))
                    where.And(u => u.name.Contains(name));
                var families = _context.Families
                    .Where(where)
                    .Skip(start).Take(pagesize)
                    .ToList();
                resp.code = 1;
                resp.data = new { items = families, total = families.Count() };
            }
            catch(Exception ex)
            {
                resp.code = -1;
                resp.message = $"检索出错,{ex.Message},{ex.StackTrace}";
            }
            return Json(resp);
        }

        /// <summary>
        /// 获取家庭成员
        /// </summary>
        /// <param name="family_id"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        //[ValidateAntiForgeryToken]
        public IActionResult GetFamilyMembers(Guid family_id, int pageindex = 1, int pagesize = 15)
        {
            Response resp = new Response();
            try
            {
                int start = (pageindex - 1) * pagesize;
                var members = _context.Members
                    .Where(u => u.family.id == family_id)
                    .Skip(start).Take(pagesize)
                    .Select(u => new { u.name, u.idcard, u.mobile, u.address, u.companyName, u.companyPlace, u.remark })
                    .ToList();
                resp.code = 1;
                resp.data = new { items = members, total = members.Count() };
            }
            catch (Exception ex)
            {
                resp.code = -1;
                resp.message = $"检索出错,{ex.Message},{ex.StackTrace}";
            }
            return Json(resp);
        }
        /// <summary>
        /// 添加家庭成员
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="family_id"></param>
        /// <returns></returns>
        [ValidateAntiForgeryToken]
        [HttpPost]
        public async Task<IActionResult> AddFamilyMember(Guid[] ids, Guid family_id)
        {
            Response resp = new Response();
            try
            {
                if (ids.Length > 0)
                {
                    var family = await _context.Families.FindAsync(family_id);
                    foreach (var id in ids)
                    {
                        var member = await _context.Members.FindAsync(id);
                        if (member.family == null)
                            member.family = family;
                    }
                    int ret = await _context.SaveChangesAsync();
                    if (ret > 0)
                    {
                        resp.code = 1;
                        resp.message = $"添加了{ret}个成员";
                    }
                }
            }
            catch(Exception ex)
            {
                resp.code = -1;
                resp.message = $"error:{ex.Message},{ex.StackTrace}";
            }
            return Json(resp);
        }

        [HttpGet]
        public async Task<IActionResult> GetMembersNoFamily()
        {
            Response resp = new Response();
            try
            {
                var members = await _context.Members.Where(u => u.family == null).ToListAsync();
                if (members.Count() > 0)
                {
                    resp.code = 1;
                    resp.message = "success";
                }
                else
                {
                    resp.message = "当前没有未添加家庭的人员";
                }
            }
            catch(Exception ex)
            {
                resp.code = -1;
                resp.message = $"error:{ex.Message},{ex.StackTrace}";
            }
            return Json(resp);
        }

        // GET: Families/Details/5
        public async Task<IActionResult> Details(Guid? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var family = await _context.Families
                .FirstOrDefaultAsync(m => m.id == id);
            if (family == null)
            {
                return NotFound();
            }

            return View(family);
        }

        // GET: Families/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Families/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("id,name,address,status,remark,Created_at,Updated_at")] Family family)
        {
            if (ModelState.IsValid)
            {
                family.id = Guid.NewGuid();
                _context.Add(family);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(family);
        }

        // GET: Families/Edit/5
        public async Task<IActionResult> Edit(Guid? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var family = await _context.Families.FindAsync(id);
            if (family == null)
            {
                return NotFound();
            }
            return View(family);
        }

        // POST: Families/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(Guid id, [Bind("id,name,address,status,remark,Created_at,Updated_at")] Family family)
        {
            if (id != family.id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(family);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!FamilyExists(family.id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(family);
        }

        // GET: Families/Delete/5
        public async Task<IActionResult> Delete(Guid? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var family = await _context.Families
                .FirstOrDefaultAsync(m => m.id == id);
            if (family == null)
            {
                return NotFound();
            }

            return View(family);
        }

        // POST: Families/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(Guid id)
        {
            var family = await _context.Families.FindAsync(id);
            _context.Families.Remove(family);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool FamilyExists(Guid id)
        {
            return _context.Families.Any(e => e.id == id);
        }
    }
}
